import random

import jwt
import numpy as np
from django.shortcuts import render
from django.contrib.auth import login, logout, authenticate
# Create your views here.
from django import http
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

# 找到轮转的数据
from rest_framework.views import APIView

from index.models import Shop
from .models import User,Cart,OrderAddress
from rest_framework.response import Response

from houduan.utils.huyi_sms.sms3 import send_sms_code


# class InsertView(APIView):
#     def get(self,request,*args,**kwargs):
#         Product.objects.create(shop_id=2)
#
#         return Response({ "code": 200})







class SMScodeView(APIView):
    def get(self,request,*args,**kwargs):
        """
        匹配并删除图形验证码
        发送短信验证码
        :param request:
        :param phone:
        :return:
        """
        # 1. 获取请求参数（路径参数+查询字符串）

        phone = request.GET.get('phone', '').strip()

        # 6. 生成短信验证码(6位数字)
        smscode_str = ""
        ranlist = np.random.randint(0, 10, 4)
        for i in ranlist:
            smscode_str += str(i)

        print('smscode:',smscode_str)



        # 8. 发送短信验证码
        ret = send_sms_code(smscode_str,phone)

        #9. 根据外部接口返回值响应前端结果
        # ret = {'code':2}
        if ret.get('code') == 2:

            terms = ''
            words = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            for _ in range(6):
                # terms = terms + str(random.sample(words, 1))
                term = random.choice(words)  # 使用random.choice直接选取一个单词而非sample
                terms += term + " "

            k = User.objects.filter(phone=phone)

            if k.exists():
                User.objects.filter(phone=phone).update(smscode=smscode_str)
                return Response({"code": 200, "smscode": smscode_str})

            User.objects.create(phone=phone, smscode=smscode_str,
                                headimgurl='http://106.54.24.34/logo1.png',
                                nickname=terms, token='123')
            return Response({"code": 200, "smscode": smscode_str})





class LoginSView(APIView):
    """用户名登录视图"""
    def post(self,request,code):
        """
        显示登录首页
        :param request:
        :return:
        """
        scode  = User.objects.filter(smscode=code)
        if scode != '':
            b = {'code': code}
            token = jwt.encode(b, 'sercet', algorithm='HS256')
            User.objects.filter(smscode=code).update(token=token)



        return Response({'token':token,"code":200,})


class UserInfoView(APIView):
    """用户名登录视图"""
    def get(self,request,code):

        obj  = User.objects.filter(smscode=code).first()

        return Response({'headimgurl': obj.headimgurl.__str__(), "nickname": obj.nickname,"code": 200, })




class GetCartList(APIView):
    """用户名登录视图"""
    def get(self,request,*args,**kwargs):

        token = request.GET.get('token', '').strip()

        user = User.objects.filter(token = token).first()
        carts = Cart.objects.filter(user_id = user.id).all()

        data = []
        for instance in carts:
            data.append({
                'blessing': instance.blessing,
                'count': instance.count,
                'createTime': instance.create_time,
                'goodsId': instance.shop_id,
                'imageUrl': instance.imageUrl.__str__(),
                'name': instance.name,
                'price': instance.price,
                'updateTime': instance.update_time,
            })

        return Response({"data": data, "code": 200,"message":"成功"})







class AddToCart(APIView):
    """用户名登录视图"""
    def get(self,request,goodsId,count):

        token = request.GET.get('token','').strip()
        blessing = request.GET.get('blessing','').strip()

        print(count)
        print(goodsId)
        try:
            count = int(count)
        except ValueError:
            return Response("Invalid count value, must be an integer.")

        if token != "":
            user = User.objects.filter(token=token).first()

            shop = Shop.objects.filter(id=goodsId).first()

            Cart.objects.create(blessing=blessing, isChecked=1, name=shop.name,imageUrl=shop.imageUrl.__str__(),
                                price=shop.price, shop_id=shop.id, user_id=user.id,count=count)
            return Response({"data": "", "code": 200, "message": "成功"})

        cart = Cart.objects.filter(shop_id = goodsId).first()
        cart.count += count
        cart.save()
        return Response({"data": "", "code": 200, "message": "成功"})



class CheckCart(APIView):

    def get(self, request, goodsId, isChecked):
        cart = Cart.objects.filter(shop_id=goodsId).update(isChecked=isChecked)
        return Response({"data": "", "code": 200, "message": "成功"})


class DeleteCart(APIView):
    def get(self, request, goodsId):
        Cart.objects.filter(shop_id=goodsId).delete()
        return Response({"data": "", "code": 200, "message": "成功"})


class FindAddress(APIView):
    def get(self, request,*args,**kwargs):
        token = request.GET.get('token', '').strip()
        user = User.objects.filter(token=token).first()
        address = OrderAddress.objects.filter(user_id=user.id).all()
        data = []
        for instance in address:
            data.append({
                'address': instance.address,
                'cityCode': instance.cityCode,
                'cityName': instance.cityName,
                'createTime': instance.create_time,
                'districtCode': instance.districtCode,
                'districtName': instance.districtName,
                'fullAddress': instance.fullAddress,
                'id': instance.id,
                'isDefault': instance.isDefault,
                'isDeleted': instance.isDeleted,
                'name': instance.name,
                'phone': instance.phone,
                'provinceCode': instance.provinceCode,
                'provinceName': instance.provinceName,
                'tagName': instance.tagName,
                'updateTime': instance.update_time,
                'userId': instance.user_id
            })

        return Response({"addressList": data, "swiperCellQueue":[],"code": 200,"message":"成功"})

class DeleteAddress(APIView):
    def get(self, request,id):
        OrderAddress.objects.filter(id=id).delete()
        return Response({"code": 200, "data":'',"message": "成功"})

class AddAddress(APIView):
    def post(self, request, *args, **kwargs):

        address = request.data.get('address', '').strip()
        cityCode = request.data.get('cityCode', '').strip()
        cityName = request.data.get('cityName', '').strip()
        districtCode = request.data.get('districtCode', '').strip()
        districtName = request.data.get('districtName', '').strip()
        fullAddress = request.data.get('fullAddress', '').strip()
        isDefault = int(request.data.get('isDefault', '0'))
        name = request.data.get('name', '').strip()
        phone = request.data.get('phone', '').strip()
        provinceCode = request.data.get('provinceCode', '').strip()
        provinceName = request.data.get('provinceName', '').strip()

        OrderAddress.objects.create(address=address,cityCode=cityCode,cityName=cityName,
                                    districtCode=districtCode,districtName=districtName,
                                    fullAddress=fullAddress,isDefault=isDefault,name=name,phone=phone,
                                    provinceCode=provinceCode,provinceName=provinceName,user_id=user.id)

        return Response({"code": 200, "data": '', "message": "成功"})

class UpdateAddress(APIView):
    def post(self, request, *args, **kwargs):
        token = request.data.get('token', '').strip()
        user = User.objects.filter(token=token).first()

        address = request.data.get('address', '').strip()
        cityCode = request.data.get('cityCode', '').strip()
        cityName = request.data.get('cityName', '').strip()
        districtCode = request.data.get('districtCode', '').strip()
        districtName = request.data.get('districtName', '').strip()
        fullAddress = request.data.get('fullAddress', '').strip()
        id = int(request.data.get('id', '0'))
        isDefault = int(request.data.get('isDefault', '0'))
        isDeleted = int(request.data.get('isDeleted', '0'))
        name = request.data.get('name', '').strip()
        phone = request.data.get('phone', '').strip()
        provinceCode = request.data.get('provinceCode', '').strip()
        provinceName = request.data.get('provinceName', '').strip()

        OrderAddress.objects.filter(id=id).update(address=address,cityCode=cityCode,cityName=cityName,
                                    districtCode=districtCode,districtName=districtName,
                                    fullAddress=fullAddress,isDefault=isDefault,isDeleted=isDeleted,
                                    name=name,phone=phone,
                                    provinceCode=provinceCode,provinceName=provinceName,user_id=user.id)

        if isDefault == 1:
        # 使用exclude方法排除特定id的记录，然后批量更新其余满足条件的记录为非默认
            OrderAddress.objects.filter(
                user=user,
                isDefault=1
            ).exclude(
                id=id
            ).update(
                isDefault=0
            )
        return Response({"code": 200, "data": '', "message": "成功"})


class InfoAddress(APIView):
    def get(self, request,id):
        ord = OrderAddress.objects.filter(id=id).all()

        data = []
        for instance in ord:
            data.append({
                'address': instance.address,
                'cityCode': instance.cityCode,
                'cityName': instance.cityName,
                'createTime': instance.create_time,
                'districtCode': instance.districtCode,
                'districtName': instance.districtName,
                'fullAddress': instance.fullAddress,
                'id': instance.id,
                'isDefault': instance.isDefault,
                'isDeleted': instance.isDeleted,
                'name': instance.name,
                'phone': instance.phone,
                'provinceCode': instance.provinceCode,
                'provinceName': instance.provinceName,
                'tagName': instance.tagName,
                'updateTime': instance.update_time,
                'userId': instance.user_id
            })
        return Response({"data": data[0], "code": 200,"message":"成功"})


class GetOrderAddress(APIView):
    def get(self, request, *args, **kwargs):
        token = request.GET.get('token', '').strip()
        user = User.objects.filter(token=token).first()

        ord = OrderAddress.objects.filter(user_id=user,isDefault=1)
        data = []
        for instance in ord:
            data.append({
                'address': instance.address,
                'cityCode': instance.cityCode,
                'cityName': instance.cityName,
                'createTime': instance.create_time,
                'districtCode': instance.districtCode,
                'districtName': instance.districtName,
                'fullAddress': instance.fullAddress,
                'id': instance.id,
                'isDefault': instance.isDefault,
                'isDeleted': instance.isDeleted,
                'name': instance.name,
                'phone': instance.phone,
                'provinceCode': instance.provinceCode,
                'provinceName': instance.provinceName,
                'tagName': instance.tagName,
                'updateTime': instance.update_time,
                'userId': instance.user_id
            })

        return Response({"orderAddress": data[0], "code": 200, "message": "成功"})

class GetTrade(APIView):
    def get(self, request, *args, **kwargs):
        token = request.GET.get('token', '').strip()
        user = User.objects.filter(token=token).first()

        carts = Cart.objects.filter(user_id=user,isChecked=1).all()
        data = []
        total_count = 0
        total_price = 0

        for instance in carts:
            data.append({
                'blessing': instance.blessing,
                'count': instance.count,
                'createTime': instance.create_time,
                'goodsId': instance.shop_id,
                'imageUrl': instance.imageUrl.__str__(),
                'name': instance.name,
                'price': instance.price,
                'updateTime': instance.update_time,
            })
            total_count += instance.count
            total_price += instance.price * instance.count


        return Response({"data":{"cartVoList": data,"totalAmount":total_price ,
                         "totalCount":total_count},
                         "code": 200, "message": "成功"})

import os,sys

class FileUp(APIView):
    def post(self, request, *args, **kwargs):

        uploaded_file = request.FILES.get('file')
        token = request.META.get('HTTP_TOKEN')


        # 保存文件到服务器
        if uploaded_file:
            # 保存文件到服务器
            # 注意：根据实际情况调整文件名和存储路径
            filename = default_storage.save(uploaded_file.name, uploaded_file)
            # 构建文件的URL
            file_url = default_storage.url(filename)
        print(file_url)
        # BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        # BASE_DIR = BASE_DIR+file_url
        # print(BASE_DIR)
        #
        # User.objects.filter(token=token).update(headimgurl = file_url)

        return Response({ "code": 200, "message": "成功"})
